import { ref, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance } from 'element-plus'

interface CrudOptions<T = any> {
  // API 方法
  listApi: (params: any) => Promise<any>
  addApi: (data: any) => Promise<any>
  updateApi: (data: any) => Promise<any>
  deleteApi: (id: number) => Promise<any>
  batchDeleteApi?: (ids: number[]) => Promise<any>
  // 表单校验规则
  formRules?: Record<string, any[]>
  // 默认表单数据
  defaultForm: T
}

export function useCrud<T = any>(options: CrudOptions<T>) {
  // 查询参数
  const queryParams = ref({
    pageNum: 1,
    pageSize: 10,
    keyword: '',
    ...options.defaultForm // 默认表单数据
  })

  // 加载状态
  const loading = ref(false)

  // 列表数据
  const list = ref([])
  const total = ref(0)

  // 选中的数据ID
  const selectedIds = ref<number[]>([])

  // 对话框
  const dialog = reactive({
    visible: false,
    title: '',
    type: ''
  })

  // 表单
  const formRef = ref<FormInstance>()
  const form = ref<T>({ ...options.defaultForm })

  // 获取列表数据
  const getList = async () => {
    loading.value = true
    try {
      const res = await options.listApi(queryParams.value)
      if (res.code === 200) {
        list.value = res.data.records
        total.value = res.data.total
      }
    } catch (error: any) {
      ElMessage.error(error.message || '获取列表失败')
    } finally {
      loading.value = false
    }
  }

  // 查询操作
  const handleQuery = () => {
    queryParams.value.pageNum = 1
    getList()
  }

  // 重置查询
  const handleReset = () => {
    queryParams.value = {
      pageNum: 1,
      pageSize: 10
    }
    handleQuery()
  }

  // 选择项变化
  const handleSelectionChange = (selection: any[]) => {
    selectedIds.value = selection.map(item => item.id)
  }

  // 新增
  const handleAdd = () => {
    dialog.type = 'add'
    dialog.title = '新增'
    dialog.visible = true
    form.value = { ...options.defaultForm }
  }

  // 修改
  const handleUpdate = (row: any) => {
    dialog.type = 'update'
    dialog.title = '修改'
    dialog.visible = true
    form.value = { ...row }
  }

  // 提交表单
  const submitForm = async () => {
    if (!formRef.value) return
    
    try {
      await formRef.value.validate()
      if (dialog.type === 'add') {
        await options.addApi(form.value)
      } else {
        await options.updateApi(form.value)
      }
      ElMessage.success(dialog.type === 'add' ? '新增成功' : '修改成功')
      dialog.visible = false
      getList()
    } catch (error: any) {
      ElMessage.error(error.message || (dialog.type === 'add' ? '新增失败' : '修改失败'))
    }
  }

  // 删除
  const handleDelete = async (row: any) => {
    try {
      await ElMessageBox.confirm('确认要删除该数据吗？', '提示', {
        type: 'warning'
      })
      await options.deleteApi(row.id)
      ElMessage.success('删除成功')
      getList()
    } catch (error: any) {
      if (error !== 'cancel') {
        ElMessage.error(error.message || '删除失败')
      }
    }
  }

  // 批量删除
  const handleBatchDelete = async () => {
    if (!selectedIds.value.length) {
      ElMessage.warning('请选择要删除的数据')
      return
    }
    if (!options.batchDeleteApi) {
      ElMessage.warning('未配置批量删除接口')
      return
    }

    try {
      await ElMessageBox.confirm('确认要删除选中的数据吗？', '提示', {
        type: 'warning'
      })
      await options.batchDeleteApi(selectedIds.value)
      ElMessage.success('删除成功')
      getList()
    } catch (error: any) {
      if (error !== 'cancel') {
        ElMessage.error(error.message || '删除失败')
      }
    }
  }

  return {
    queryParams,
    loading,
    list,
    total,
    selectedIds,
    dialog,
    formRef,
    form,
    getList,
    handleQuery,
    handleReset,
    handleSelectionChange,
    handleAdd,
    handleUpdate,
    submitForm,
    handleDelete,
    handleBatchDelete
  }
} 